﻿@using System.ComponentModel.DataAnnotations;
@using System.Text.Json;

<Form @ref="form"
      Model="@model"
      OnFinish="OnFinish"
      OnFinishFailed="OnFinishFailed"
      LabelColSpan="8"
      WrapperColSpan="16">
    <FormItem Label="Note">
        <Input @bind-Value="@context.Note" />
    </FormItem>
    <FormItem Label="Gender">
        <Select @bind-Value="@context.Gender"
                TItemValue="string"
                TItem="string"
                DefaultActiveFirstOption="false"
                Placeholder="Select an option and the input above will be changed"
                OnSelectedItemChanged="OnGenderChanged">
            <SelectOptions>
                <SelectOption TItemValue="string" TItem="string" Value="@("Male")" Label="Male" />
                <SelectOption TItemValue="string" TItem="string" Value="@("Female")" Label="Female" />
                <SelectOption TItemValue="string" TItem="string" Value="@("Other")" Label="Other" />
            </SelectOptions>
        </Select>
    </FormItem>
    <FormItem Label="DateRange">
        <RangePicker @bind-Value="context.DateRange" />
    </FormItem>
    <FormItem WrapperColOffset="8" WrapperColSpan="16">
        <Button Type="@ButtonType.Primary" HtmlType="submit">
            Submit
        </Button>
        <Button OnClick="Reset">
            Reset
        </Button>
        <Button Type="@ButtonType.Link" OnClick="OnFill">
            Fill form
        </Button>
    </FormItem>
</Form>
@code
{
    public class Model
    {
        [Required]
        public string Note { get; set; }
        [Required]
        public string Gender { get; set; }
        [Required]
        public DateTime?[] DateRange { get; set; }
    }

    private Model model = new Model();
    private Form<Model> form;

    private void OnFill(MouseEventArgs args)
    {
        model.Note = "Hello Sir!";
        model.Gender = "Male";
        model.DateRange = new DateTime?[] { DateTime.Now, DateTime.Now.AddDays(1) };

        Console.WriteLine($"form ref:{form}");
    }

    private void Reset(MouseEventArgs args)
    {
        form.Reset();
    }

    private void OnFinish(EditContext editContext)
    {
        Console.WriteLine($"Success:{JsonSerializer.Serialize(model)}");
    }

    private void OnFinishFailed(EditContext editContext)
    {
        Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
    }

    private void OnGenderChanged(string gender)
    {
        switch (gender)
        {
            case "Male":
                form.Model.Note = "Hello Sir!";
                break;
            case "Female":
                form.Model.Note = "Hello Madam!";
                break;
            case "Other":
                form.Model.Note = "Hello there!";
                break;
            default:
                break;
        }
    }
}